package com.little.wxlogin.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.little.wxlogin.constant.SystemConstant;
import com.little.wxlogin.pojo.User;
import com.little.wxlogin.mapper.UserMapper;
import com.little.wxlogin.pojo.ro.AppletsWxLoginRO;
import com.little.wxlogin.pojo.ro.GetWxUserInfoRO;
import com.little.wxlogin.pojo.ro.WxUserInfoRO;
import com.little.wxlogin.pojo.vo.ReWxUserInfoVO;
import com.little.wxlogin.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.little.wxlogin.util.WxLoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小王八
 * @since 2022-10-30
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public ReWxUserInfoVO loginByWx(String code) {
        //1.通过code 获取到用户的微信信息
        WxUserInfoRO wxUserInfoRO = WxLoginUtil.toWxLogin(code);
        //2.数据库对比 unionid 是否已有信息 如果没有就保持数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //通过查询pk_id 索引优化查询 无需回表查询用户信息 索引 unionid
        queryWrapper.select("pk_id").eq("unionid",wxUserInfoRO.getUnionid());
        User user = getOne(queryWrapper);
        log.info("数据库查询用户是否已有账号==空则没有==={}====",user);
        if (ObjectUtil.isEmpty(user)){
            save(new User().setNickname(wxUserInfoRO.getNickname()).setHeadImgUrl(wxUserInfoRO.getHeadimgurl()).setUnionId(wxUserInfoRO.getUnionid()));
        }
        return new ReWxUserInfoVO().setNickname(wxUserInfoRO.getNickname()).setHeadimgurl(wxUserInfoRO.getHeadimgurl());
    }

    @Override
    public ReWxUserInfoVO loginByWxApplets(String code) {
        //1.通过code 获取到用户的微信信息
        AppletsWxLoginRO getWxUserInfoRO = WxLoginUtil.toAppletsWxLogin(code);
        //2.数据库对比 unionid 是否已有信息 如果没有就保持数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //通过查询pk_id 索引优化查询 无需回表查询用户信息 索引 unionid
        queryWrapper.eq("unionid",getWxUserInfoRO.getUnionid());
        User user = getOne(queryWrapper);
        log.info("数据库查询用户是否已有账号==空则没有==={}====",user);
        if (ObjectUtil.isEmpty(user)){
            //定义用户默认信息
            long userId = IdUtil.getSnowflakeNextId();
            String userName= "足球"+ RandomUtil.randomStringUpper(SystemConstant.NUM_FOUR);
            save(new User().setPkId(userId).setNickname(userName).setUnionId(getWxUserInfoRO.getUnionid()));
            return new ReWxUserInfoVO().setPkId(userId).setNickname(userName);
        }
        return new ReWxUserInfoVO().setPkId(user.getPkId()).setNickname(user.getNickname()).setHeadimgurl(user.getHeadImgUrl());
    }
}
